package com.example.medicinetime;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class Alarm {
    public static final String TAG = "Alarm";

    public static int setRepeatingAlarmTimer(Context context, long firstTime,
                                              long cycTime, String action, int AlarmManagerType) {

        Intent myIntent = new Intent();
        myIntent.setAction(action);
        //给每个闹钟设置不同ID防止覆盖
        SharedPreferences sp=context.getSharedPreferences("myalarm", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(context);
        int alarmId =sp.getInt("alarmId",0);
        savetoSP(context,alarmId);
        PendingIntent sender = PendingIntent.getBroadcast(context, alarmId, myIntent, 0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.setRepeating(AlarmManagerType, firstTime, cycTime, sender);        //param1：闹钟类型，param1：闹钟首次执行时间，param1：闹钟两次执行的间隔时间，param1：闹钟响应动作。
        Log.i(TAG, "setRepeatingAlarmTimer: 生成重复闹钟alarmId="+alarmId);
        return alarmId;
    }

    public static int setAlarmTimer(Context context, long cycTime,
                                     String action, int AlarmManagerType) {
        Intent myIntent = new Intent();
        myIntent.setAction(action);
        //给每个闹钟设置不同ID防止覆盖
        SharedPreferences sp=context.getSharedPreferences("myalarm", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(context);
        int alarmId =sp.getInt("alarmId",0);
        savetoSP(context,alarmId);
        PendingIntent sender = PendingIntent.getBroadcast(context, alarmId, myIntent, 0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManagerType, cycTime, sender);
        Log.i(TAG, "setRepeatingAlarmTimer: 生成单次闹钟alarmId="+alarmId);
        return alarmId;
    }

    public static void cancelAlarmTimer(Context context, String action,int alarmID) {
        Log.i(TAG, "cancelAlarmTimer: 删除闹钟alarmID="+alarmID);
        Intent myIntent = new Intent();
        myIntent.setAction(action);
        PendingIntent sender = PendingIntent.getBroadcast(context, alarmID, myIntent,0);
        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(sender);
    }

    private static void savetoSP(Context context, int alarmId) {
        SharedPreferences sp=context.getSharedPreferences("myalarm", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(context);

        SharedPreferences.Editor editor= sp.edit();
        editor.putInt("alarmId", ++alarmId);
        editor.apply();
    }

}
